package com.tongda.menu.util;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.tongda.core.common.Constants;
import com.tongda.core.common.KernalApplication;
import com.tongda.core.repository.MenuCartDao;
import com.tongda.menu.R;
import com.tongda.menu.activity.BaseActivity;

/**
 * 这个ActivityUtil工具类只针对电子菜谱
 * */
public final class ActivityMenuUtil {

    public static DisplayImageOptions getImageOptions(){
    	DisplayImageOptions options = new DisplayImageOptions.Builder()
    	.showImageOnLoading(R.drawable.nopic)
		.showImageOnLoading(R.drawable.nopic)
		.showImageForEmptyUri(R.drawable.nopic)
		.showImageOnFail(R.drawable.nopic)
		.imageScaleType(ImageScaleType.EXACTLY)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.displayer(new FadeInBitmapDisplayer(100)) 
//		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.resetViewBeforeLoading(true)
		.build();
    	return options;
    }
    
    /**
     * 生成ImageLoader对象并初始化
     * */
    public static ImageLoader getImageLoader(Context context){
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context.getApplicationContext())
		.defaultDisplayImageOptions(getImageOptions())
    	.threadPoolSize(3)//线程池内加载的数量
        .threadPriority(Thread.NORM_PRIORITY - 2)
        .denyCacheImageMultipleSizesInMemory()
        .tasksProcessingOrder(QueueProcessingType.LIFO)
        .memoryCacheExtraOptions(480, 800) // max width, max height，即保存的每个缓存文件的最大长宽 
        .memoryCache(new WeakMemoryCache()) // You can pass your own memory cache implementation/你可以通过自己的内存缓存实现  
        .memoryCacheSize(2 * 1024 * 1024)    
        .diskCacheSize(50 * 1024 * 1024)
        .diskCacheFileNameGenerator(new Md5FileNameGenerator())
        .imageDownloader(new BaseImageDownloader(context.getApplicationContext(), 5 * 1000, 30 * 1000)) // connectTimeout (5 s), readTimeout (30 s)超时时间  
//        .writeDebugLogs()// Remove for release app
        .build(); 
    	
    	ImageLoader imageloader = ImageLoader.getInstance();
    	if(!imageloader.isInited()){
    		imageloader.init(config);
    	}
    	return imageloader;   
    }
    
    /**
     * ImageLoader加载图片
     * */
    public  static void loadImage( final ImageLoader imageLoader, String url, final ImageView loadView,final DisplayImageOptions options,final Context context){
  		imageLoader.displayImage(url,loadView,options ,
  				new ImageLoadingListener() {
  					@Override
  					public void onLoadingStarted(String imageUri, View view) {
  					}

					@Override
  					public void onLoadingFailed(String imageUri, View view,
  							FailReason failReason) {
  						String message = null;
  						switch (failReason.getType()) {
  						case IO_ERROR:
  							message = "Input/Output error";
  							break;
  						case DECODING_ERROR:
  							message = "can not be decoding";
  							break;
  						case NETWORK_DENIED:
  							message = "Downloads are denied";
  							break;
  						case OUT_OF_MEMORY:
  							message = "内存不足";
							Toast.makeText(context, message, Toast.LENGTH_SHORT)
							.show();
  							break;
  						case UNKNOWN:
  							message = "Unknown error";
  							break;
  						}
  					}

  					@Override
  					public void onLoadingComplete(String imageUri, View view,
  							Bitmap loadedImage) {
  					}

  					@Override
  					public void onLoadingCancelled(String paramString,
  							View paramView) {
  					}
  				});
      }
    
	/**
	 * @Description: 创建动画层
	 * @param
	 * @return void
	 * @throws
	 */
	public static ViewGroup createAnimLayout(Activity activity ) {
		ViewGroup rootView = (ViewGroup) activity.getWindow().getDecorView();
		LinearLayout animLayout = new LinearLayout(activity);
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.MATCH_PARENT,
				LinearLayout.LayoutParams.MATCH_PARENT);
		animLayout.setLayoutParams(lp);
		animLayout.setId(Integer.MAX_VALUE);
		animLayout.setBackgroundResource(android.R.color.transparent);
		rootView.addView(animLayout);
		return animLayout;
	}
	public static View addViewToAnimLayout(final ViewGroup vg, final View view,
			int[] location) {
		int x = location[0];
		int y = location[1];
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
				LinearLayout.LayoutParams.WRAP_CONTENT,
				LinearLayout.LayoutParams.WRAP_CONTENT);
		lp.leftMargin = x;
		lp.topMargin = y;
		view.setLayoutParams(lp);
		return view;
	}
	
	/**
	 * 重启应用的方法
	 * */
	
	public static void restartApp(Activity activity){
		MenuCartDao ordered_dish_dao = MenuCartDao.getInstance(activity);
		KernalApplication 	application = KernalApplication.getInstance();
		//这里不需要清空菜类表和菜肴表的某些列值 应为重启应用后再次更新数据的时候会把这两个表全部清空重新入值
 	    ordered_dish_dao.clearOrderDish();
 	    BaseActivity.setUpdateDishes(true);
 		application.setBillNotes(null);
 		application.setMenuMainIsRefresh(false);
 		application.setMenuSelectedTable(null);
 		
         Intent i = activity.getBaseContext().getPackageManager() 
         		.getLaunchIntentForPackage(activity.getBaseContext().getPackageName()); 
         		i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); 
        activity.startActivity(i);
	}
	
	/** 
     * 检测网络是否连接 
     * @return 
     */  
    public static boolean checkNetworkState(Context context) {  
        boolean flag = false;  
        //得到网络连接信息  
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
        //去进行判断网络是否连接  
        if (manager.getActiveNetworkInfo() != null) {  
            flag = manager.getActiveNetworkInfo().isAvailable();  
        }  
//        if (!flag) {  
//            setNetwork((Activity) context);  
//        } else {  
//            isNetworkAvailable(context);  
//        }  
        return flag;  
    } 
    
    /** 
     * 网络未连接时，调用设置方法 
     */  
    public static void setNetwork(final Activity activity){  
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);  
        builder.setIcon(R.drawable.ic_launcher);  
        builder.setTitle("网络提示信息");  
        builder.setMessage("网络不可用，如果继续，请先设置网络！");  
        builder.setPositiveButton("设置", new OnClickListener() {  
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
                Intent intent = null;  
                /** 
                 * 判断手机系统的版本！如果API大于10 就是3.0+ 
                 * 因为3.0以上的版本的设置和3.0以下的设置不一样，调用的方法不同 
                 */  
                if (android.os.Build.VERSION.SDK_INT > 10) {  
                    intent = new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS);  
                } else {  
                    intent = new Intent();  
                    ComponentName component = new ComponentName(  
                            "com.android.settings",  
                            "com.android.settings.WirelessSettings");  
                    intent.setComponent(component);  
                    intent.setAction("android.intent.action.VIEW");  
                }  
                activity.startActivity(intent);  
            }  
        });  
  
        builder.setNegativeButton("取消", new OnClickListener() {  
            @Override  
            public void onClick(DialogInterface dialog, int which) {  
  
            }  
        });  
        builder.create();  
        builder.show();  
    }  
      
    /** 
     * 网络已经连接，然后去判断是wifi连接还是GPRS连接 
     * 设置一些自己的逻辑调用 
     */  
    public static void isNetworkAvailable(Context context){  
        ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);  
        State gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();  
        State wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();  
        if(gprs == State.CONNECTED || gprs == State.CONNECTING){  
            Toast.makeText(context, "wifi is open! gprs", Toast.LENGTH_SHORT).show();  
        }  
        if(wifi == State.CONNECTED || wifi == State.CONNECTING){  
            Toast.makeText(context, "wifi is open! wifi", Toast.LENGTH_SHORT).show();  
        }  
          
    } 
    
}
